﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ToolGood.Words;

public static class SensitiveWordManager
{
    public const string dirName = "sensitive_word";
    public static bool showStar = true;
    static bool inited;
    static IllegalWordsSearch iwords;
    public static System.Func<string, string> externalLoader;

    public static void Reset()
    {
        inited = false;
        iwords = null;
    }

    static void Init()
    {
        if (inited)
        {
            return;
        }

        inited = true;

        string path = dirName + "/sensitive_word";

        string str = null;
        if (externalLoader != null)
        {
            str = externalLoader(path);
        }

        if (str == null)
        {
            TextAsset temp = ResourceManager.LoadAsset<TextAsset>(path);
            str = temp.text;
        }

        iwords = new IllegalWordsSearch();
        string[] keywords = str.Split(',');
        iwords.SetKeywords(keywords);
    }

    public static bool Convert(string str, ref string newStr)
    {
        Init();

        List<IllegalWordsSearchResult> results = iwords.FindAll(str);

        if (results.Count > 0)
        {
            if (showStar)
            {
                char[] arr = str.ToCharArray();

                for (int i = 0; i < results.Count; i++)
                {
                    IllegalWordsSearchResult result = results[i];
                    for (int j = result.Start; j <= result.End; j++)
                    {
                        arr[j] = '*';
                    }
                }

                newStr = new string(arr);
            }
            else
            {
                newStr = str;
                for (int i = results.Count - 1; i >= 0; i--)
                {
                    IllegalWordsSearchResult result = results[i];
                    newStr = newStr.Insert(result.End + 1, "))");
                    newStr = newStr.Insert(result.Start, "((");
                }
            }

            return true;
        }

        return false;
    }

    public static bool ContainAny(string str)
    {
        Init();
        return iwords.ContainsAny(str);
    }
}
